import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hkzf_flutter/dio/room_item.dart';
import 'package:hkzf_flutter/pages/search/room/room_item.dart';
import 'package:hkzf_flutter/scoped_model/auth_model.dart';
import 'package:hkzf_flutter/utils/dio_http.dart';
import 'package:hkzf_flutter/utils/scoped_model_helper.dart';
import 'package:hkzf_flutter/widgets/common_floating_button.dart';
import 'package:hkzf_flutter/widgets/room_list_item.dart';

// 房屋管理页面
class RoomManagePage extends StatefulWidget {
  const RoomManagePage({super.key});

  @override
  State<RoomManagePage> createState() => _RoomManagePageState();
}

class _RoomManagePageState extends State<RoomManagePage> {
  List<RoomItem> availableDataList = [];
  //获取数据
  _getData() async {
    var auth = ScopedModelHelper.getModel<AuthModel>(context);
    if(!auth.isLogin) return;
    var token = auth.token;
    String path = '/user/houses';
    var res =await DioHttp.of(context).get(path,null,token);
    var resMap = json.decode(res.toString());
    List listMap = resMap['body'];
    print('数据集:$listMap');
    var dataList = listMap.map((json)=>RoomItem.fromJson(json)).toList();
    setState(() {
      availableDataList = dataList;
    });

  }
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      _getData();
    });
  }
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 0,
      length: 2, 
      child: Scaffold(
        appBar: AppBar(
          title: const Text("房屋管理"),
          backgroundColor: Colors.green,
          bottom: const TabBar(
            labelColor: Colors.white,// 选中文本颜色
            unselectedLabelColor: Colors.black,// 未选中文本颜色
            indicatorColor: Colors.white,// 选中下划线颜色
            tabs: [
              Tab(text: "空置"),
              Tab(text: "已租")
            ],
          ),
        ),
        floatingActionButton:CommonFloatingButton(
          title: "发布房源",
          onTap: (){
            var result = Navigator.pushNamed(context, '/roomAdd');
            result.then((value) {
              if(value  == value){
                // 重新刷新发布发源信息
                _getData();
              }
            });
          },
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        body: TabBarView(children: [
          ListView(
            children: availableDataList.map((item)=>RoomListItem(data: item,)).toList(),
          ),
          ListView(
            children: roomList.map((item)=>RoomListItem(data: item,)).toList(),
          )
          ],
        ),
      )
    );
  }
}